﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MarvellousWorks.PracticalPatternNet8.Concept.Indexer;

/// <summary>
/// 具有联合索引特点的实体类型
/// </summary>
public struct Employee
{
    public string? FirstName;
    public string? FamilyName;
    public string? Title;
    public Employee(DataRow row)
    {
        FirstName = row["FirstName"] as string;
        FamilyName = row["FamilyName"] as string;
        Title = row["Title"].ToString();
    }
}
public class Staff
{
    static DataTable data = new DataTable();
    /// <summary>
    /// 准备数据
    /// </summary>
    /// <remarks>实际数据应该会从数据库等持久化层渠道获得</remarks>
    static Staff()
    {
        data.Columns.Add("FirstName", typeof(string));
        data.Columns.Add("FamilyName", typeof(string));
        data.Columns.Add("Title", typeof(string));
        data.Rows.Add("John", "Doe", "Manager");
        data.Rows.Add("Jane", "Doe", "Assistant");
        data.Rows.Add("Jane", "Smith", "Developer");
        data.Rows.Add("Bob", "Brown", "Developer");
        data.Rows.Add("Alice", "Johnson", "Designer");
        data.PrimaryKey = new DataColumn[] { data.Columns["FirstName"]!, data.Columns["FamilyName"]! };
    }

    // 基于联合主键的索引器
    public Employee this[string firstName, string familyName]
    {
        get
        {
            DataRow? row = data.Rows.Find(new object[] { firstName, familyName });
            if (row == null)
                throw new IndexOutOfRangeException($"Employee with name {firstName} {familyName} not found.");
            return new Employee(row);
        }
    }
}
